#include "MemoryRegion.h"

#include <iostream>

MemoryRegion::shared_data MemoryRegion::data()
{
	return data_;
}

const MemoryRegion::shared_data MemoryRegion::data() const
{
	return data_;
}

const MemoryAddress MemoryRegion::findString( const std::string& str, address_t offset ) const
{
	for (address_t addr = offset != 0 ? offset - bounds_.begin() : 0; addr < bounds_.length() - str.length() + 1; addr++)
	{
		for (size_t i = 0; i < str.length(); i++)
		{
			if (data_.get()[addr+i] != str[i])
			{
				break;
			}
			if (i == str.length() - 1 && data_.get()[addr+i+1] == 0)
				return MemoryAddress(addr + bounds_.begin());
		}
	}
	return 0;
}

const MemoryAddress MemoryRegion::findPattern( const std::string& pattern, const std::vector<byte>& bytes, const MemoryAddress offset ) const
{
	if (pattern.size() != bytes.size())
	{
		std::cout << "Patternsize (" << pattern.size() << ") and bytesize (" << bytes.size() << ") differ!" << std::endl;
	}

	for (address_t b = offset != 0 ? offset - bounds_.begin() : 0; b < bounds_.length() - pattern.size(); b++)
	{
		for (size_t i = 0; i < pattern.size(); i++)
		{
			if (pattern[i] == 'x' && data_.get()[b+i] != bytes[i])
				break;
			if (i == pattern.size() - 1)
				return MemoryAddress(bounds_.begin()  + b);
		}
	}
	return 0;
}

MemoryRegion::MemoryRegion( const MemoryBounds& bounds_, MemoryReader& reader ) : bounds_(bounds_), data_( new byte[bounds_.length()])
{
	reader.read(bounds_.begin(), bounds_.length(), data_.get());
}

MemoryRegion::MemoryRegion( const MemoryRegion&& other ) : data_(other.data_), bounds_(other.bounds_)
{

}

const MemoryBounds& MemoryRegion::bounds() const
{
	return bounds_;
}
